#!/usr/bin/python2 -S
# -*- coding: utf-8 -*-
import sys
sys.setdefaultencoding("utf-8")
import site
import traceback

import subprocess
import re

import parser 
from parser import report_parser

import dao
from   dao import db_operator



MY_NAME='fdra'

# 工具入口

def print_usage( argv0 = MY_NAME ):
    print "Usage:"
    print "  %s import    <日报文件>   导入逐日盯市日报文件" % argv0
    print "  %s importdir <日报目录>   导入指定目录下所有逐日盯市日报文件" % argv0
    print "  %s stat [lastday|YYYY-MM-DD|YYYY-MM ]  显示按品种的盈亏统计"         % argv0
    print "  %s stat [daily | daily_top]   显示每日成绩"         % argv0
    print "  %s total            显示总盈亏"       % argv0

# 处理 'importdir' 子命令
def handle_importdir( argv, argv0 = MY_NAME ):
    i = len(argv)
    if ( i < 1 ):
        print "  %s importdir <日报目录>   导入指定目录下所有逐日盯市日报文件" % argv0
        print "\n 未指定 <日报目录>\n"
        return 1

    myself = sys.argv[0]
    r = subprocess.call([ "find"
            , argv[0]
            , "-name"
            , "*.xls"
            , "-exec"
            , myself
            , "import"
            , "{}"
            , ";"
            ])
    return r 


# 处理 'import' 子命令
def handle_import( argv, argv0 = MY_NAME ):
    i = len(argv)
    if ( i < 1 ):
        print "  %s import <日报文件>     解析导入日报文件" % argv0
        print "\n 未指定 <日报文件>\n"
        return 1

    try:

        print "processing %s" % (argv[0], )
        s = report_parser.parse_single_file( argv[0]  )

        report_parser.save_report_to_db(s)


    except  Exception as e:
         (t, v, bt) = sys.exc_info()
         #print e
         traceback.print_exception(t, v, bt)

         return 2

    #s.dump()

    return 0

# 处理 'stat' 子命令
def handle_stat(argv, argv0 = MY_NAME ):
    i = len(argv)
    if ( i < 1 ):
        # 无参数
        db_operator.simplest_stat_by_target()
        print "总计:"
        db_operator.show_total()

        return 0

    what = argv[0]

    if ("lastday" == what):
        db_operator.lastday_stat_by_target()
        print "总计:"
        db_operator.lastday_total()
        return 0

    if ("daily" == what):
        print "交易日统计:"
        db_operator.daily_stat()
        return 0

    if ("daily_top" == what):
        print "交易日排行:"
        db_operator.daily_stat_sorted()
        return 0
    

    #check if is 'YYYY-MM-DD'
    reg = re.compile('^\d\d\d\d-\d\d-\d\d$')
    if reg.match(what):  
        if (i >=2 and reg.match(argv[1])):
            # stat $From  $Until 的形式
            until = argv[1]
            print "==== %s ~ %s  区间统计=====" % (what, until)
            db_operator.range_stat_by_target( what, until )
            print "总计:"
            db_operator.range_total( what, until )

        else:
            print "==== %s  日报=====" % what
            db_operator.day_stat_by_target( what )
            db_operator.day_total( what )
        return 0
 
    #check if is 'YYYY-MM'
    reg = re.compile('^\d\d\d\d-\d\d$')
    if reg.match(what): 
        db_operator.month_stat_by_target( what )
        print "总计:"
        db_operator.month_total( what )
        return 0
    
    #check if is 'YYYY'
    reg = re.compile('^\d\d\d\d$')
    if reg.match(what): 
        db_operator.year_stat_by_target( what )
        print "总计:"
        db_operator.year_total( what )
        return 0

    print "尚未实现 '%s' :(" % ( what, )
    
    return 0

# 处理 'total' 子命令
def handle_total():
    db_operator.show_total()
    return 0


def main():

    i = len(sys.argv)
    if ( i < 2 ):
        print_usage()
        return 1

    sub_command = sys.argv[1]

    if ('import' == sub_command ):
        return handle_import ( sys.argv[2:] ) 
    elif ('importdir' == sub_command ):
        return handle_importdir ( sys.argv[2:] ) 
    elif ('stat' == sub_command ):
        return handle_stat( sys.argv[2:])
    elif ('total' == sub_command ):
        return handle_total()
    elif ('help' == sub_command ):
        print_usage()
        return 1
    else:
        print "\n无效的‘子命令’ -- %s\n" % ( sub_command, )
        print_usage()
        return 1

    return 0


if __name__ == "__main__":
    r = main()
    sys.exit(r)


